<?php

/**
 * 投票
 * User: huy
 * Date: 2016/7/5
 * Time: 21:16
 */
class IsvoteControl extends Control{
    private $time1    = '2016-07-20 00:00:00';   //开始
    private $time2    = '2016-08-01 00:00:00';   //中间投票时间
    private $time3    = '2016-08-31 23:59:59';   //结束
    private $hcoin    = 0;
    private $gamecoin = 2000;//投票每一票消耗的游戏币2000
    private $limit    = 10;   //每天最多投10票
    private $level    = 30;//参加活动的等级限制

    //构造函数
    function __construct(){
        parent::__construct();
        $this->actName = '新炫舞宝贝评选';
        load_config('commonMain/onload');
        $this->zone_arr = get_dmz_game_zone();
        load_model(ACT_NAME . '/main');   //自己的main.mod
        $this->model = new MainModel();

        //重新设置活动时间（用于外网、预发布环境）
        if(file_exists(APPLICATION_ROOT . '/config/basic.cfg.php')){
            //include文件的路径，$BasicCFG就存下了.php return 的数组
            $BasicCFG = include_once APPLICATION_ROOT . '/config/basic.cfg.php';
            if(!empty($BasicCFG[YEAR][ACT]['time1']) && !empty($BasicCFG[YEAR][ACT]['time2']) && !empty($BasicCFG[YEAR][ACT]['time3']) && !empty($BasicCFG[YEAR][ACT]['level']) && !empty($BasicCFG[YEAR][ACT]['gamecoin']) && !empty($BasicCFG[YEAR][ACT]['money'])){
                $this->time1    = $BasicCFG[YEAR][ACT]['time1'];
                $this->time2    = $BasicCFG[YEAR][ACT]['time2'];
                $this->time3    = $BasicCFG[YEAR][ACT]['time3'];
                $this->level    = $BasicCFG[YEAR][ACT]['level'];
                $this->gamecoin = $BasicCFG[YEAR][ACT]['gamecoin'];
                $this->money    = $BasicCFG[YEAR][ACT]['money'];
            }
        }
    }
    /*
     * 投票
     * 1.登录，时间
     * 2.每票5000游戏币
     * 3.送小玫瑰，1玫瑰=1票，花费2个51点
      * 4.魅力值可以转换为票数  2000魅力=1票     [魅力值增加票数，1h更新一次]
     * 3.每天最多投票10票
      * 4.不能给自己投票
         */

    //游戏币——投票
    public function vote($login, $f_uin, $uin, $zoneid){
        $result = array('success' => 1);
        if(!$f_uin){
            $result['msg'] = '亲，请正确选择投票的对象~';    //送玫瑰？？？||投票   对象
            echo json_encode($result);
            exit;
        }

        //被投票的用户是否满足，被投票的条件
        //登录时间，每一票5000游戏币，每天投票10次，不能给自己投票：（没有3,4）
        $this->_vote_condition($login, $f_uin, $uin, $zoneid);
        $list = $this->model->get_item('bbpx2016_userinfo', 'uin', " uin={$f_uin} and status=5 limit 1");
        if(empty($list)){
            $result['msg'] = '亲，您选择的选手还没有通过审核哦~';
            echo json_encode($result);
            exit;
        }

        //扣游戏币
        //$status   扣游戏币的状态
        $status = $this->reduceMoney(1, $this->gamecoin, $uin, $zoneid);

        //写投票日志
        $param = array(
            'uin'       => $uin,
            'zone_id'   => $zoneid,
            'vote'      => 1,
            'money_id'  => 0,
            'f_uin'     => $f_uin,
            'status'    => $status,
            'log_time'  => date("Y-m-d H:i:s"),
            'role_name' => $_SESSION['RoleName']
        );
        $a     = $this->model->insert_data('bbpx2016_log', $param);

        if(1 == $status){   //扣游戏币成功==1
            //当前用户（投票的用户）的投票票数+1
            $re = $this->model->update_data('bbpx2016_vote', array(), "uin={$uin} limit 1", 'vote_count=vote_count+1');

            //被投票用户，票数+1
            $vote = $this->model->get_item('bbpx2016_userinfo','vote',"uin={$f_uin}");
            $vote = $vote[0]['vote'];
            $params = array(
                'vote' => $vote + 1,
            );
            $ret = $this->model->update_datas('bbpx2016_userinfo',$params, "where uin={$f_uin}");
            $result['success'] = 3;
            $result['msg']     = '亲，恭喜你投票成功';

            echo json_encode($result);
            exit;
        }else{
            //扣游戏币失败  ！=1
            $result['msg'] = '服务器繁忙，响应超时';
            echo json_encode($result);
            exit;
        }
    }

    //送玫瑰——投票
    public function buyApple($login, $uin, $zoneid, $f_uin, $num){
        $result = array('success' => 1);
        if(!$f_uin){
            $result['msg'] = '亲，请正确选择赠送玫瑰的对象~';
            echo json_encode($result);
            exit;
        }
        if($num < 1){
            $result['msg'] = '亲，至少赠送一个玫瑰哦~';
            echo json_encode($result);
            exit;
        }

        $this->is_off($login);   //时间，登录条件判断，满足
        $list = $this->model->get_item('bbpx2016_userinfo', 'role_name', " uin={$f_uin} and status=5 limit 1");
        if(empty($list)){
            $result['msg'] = '亲，您选择的选手还没有通过审核哦~';
            echo json_encode($result);
            exit;
        }

        $money              = $num * 2;
        $prm                = array();
        $prm['uin']         = $uin;
        $prm['zoneid']      = $zoneid;
        $prm['account']     = $_SESSION['LoginUser'];
        $prm['ip']          = get_client_ip_from_ns(true);
        $prm['create_time'] = date('Y-m-d H:i:s');
        $prm['money']       = $money;
        //开启事务
        mysql_query("START TRANSACTION");
        //写51点日志
        $money_id = $this->model->insert_data('bbpx2016_money_log', $prm);
        if(!$money_id){
            mysql_query("ROLLBACK");
            exit(json_encode(array('code' => '005', 'msg' => '11~~')));
        }
        /*扣除51点*/
        $oldMoney = $_SESSION['money'];
        //$status  扣钱的状态
        $status = $this->model->modifyUserMoney($uin, $zoneid, $money, 0x09020030, $oldMoney);
        if(!$status){
            mysql_query("ROLLBACK");
            exit(json_encode(array('code' => '005', 'msg' => '22~~')));
        }
        if($status != 1){
            if($status == -1){
                $result['msg'] = '亲，您的51点余额不足，请充值后再进行游戏吧';
            }else{
                $result['msg'] = '网站繁忙，请稍后再试！';
            }
            echo json_encode($result);
            exit;
        }
        $_SESSION['money'] = $oldMoney - $money;

        //写投票日志
        //$money_id  写money_log,插入的id
        $param = array(
            'uin'       => $uin,
            'zone_id'   => $zoneid,
            'vote'      => $num,
            'money_id'  => $money_id,
            'f_uin'     => $f_uin,
            'status'    => $status,
            'log_time'  => date("Y-m-d H:i:s"),
            'role_name' => $_SESSION['RoleName']
        );
        $re    = $this->model->insert_data('bbpx2016_log', $param);
        if($re){
            mysql_query("ROLLBACK");
            exit(json_encode(array('code' => '005', 'msg' => '33~~')));
        }
        if(1 == $status){
            //更新userinfo表的vote,apple_vote

            $re = $this->model->update_data('bbpx2016_userinfo', array(), "uin={$f_uin}", 'vote=vote+' . $num . ',apple_vote=apple_vote+' . $num);
            if(!$re){
                mysql_query("ROLLBACK");
                exit(json_encode(array('code' => '005', 'msg' => '44~~')));
            }
            //更新money_log表，status值
            $ret = $this->model->update_data('bbpx2016_money_log', array(), "id={$money_id}", 'status=1');
            if(!$ret){
                mysql_query("ROLLBACK");
                exit(json_encode(array('code' => '005', 'msg' => '55~~')));
            }
            $result['success'] = 3;
            $result['money']   = $_SESSION['money'];
            $result['msg']     = '亲，您成功赠送 ' . $num . ' 个玫瑰给 ' . $list[0]['role_name'];
            mysql_query("COMMIT");  //提交事务
            echo json_encode($result);
            exit;
        }else{
            mysql_query("ROLLBACK");
            $result['msg'] = '服务器繁忙，响应超时';
            echo json_encode($result);
            exit;
        }
    }

    //投票条件
    public function _vote_condition($login, $f_uin, $uin, $zoneid){
        $result = array('success' => 1);
        $time   = time();
        if($time < strtotime($this->time1)){
            $result['msg'] = '亲~本次活动尚未开始哦~';
            echo json_encode($result);
            exit;
        }
        if($time < strtotime($this->time2)){
            $result['msg'] = '现在是报名时间，投票还没开始';
            echo json_encode($result);
            exit;
        }
        if($time > strtotime($this->time3)){
            $result['msg'] = '亲，投票时间已结束~更多精彩活动请关注官网活动专区';
            echo json_encode($result);
            exit;
        }

        if($login == 0){
            $result['success'] = 2;        //未登陆
            echo json_encode($result);
            exit;
        }
        if($uin == $f_uin){
            $result['msg'] = '亲，不能自己为自己投票哦';
            echo json_encode($result);
            exit;
        }
        if(false === $this->_game_condition($uin, $zoneid)){
            $result['msg'] = '亲，您游戏角色内不足2000游戏币';
            echo json_encode($result);
            exit;
        }
        if(false === $this->_vote_time($uin, $zoneid)){
            $result['msg'] = '亲，您今天投票已满10次，您还可以通过送玫瑰来支持你喜欢的TA哦~';
            echo json_encode($result);
            exit;
        }
    }

    //判断游戏币条件
    function _game_condition($uin, $zoneid){
        load_extend('PromoterBill');
        $gm_server = new gm_server();
        $response  = $gm_server->getUserGameInfo($uin, 0, '', 0, $zoneid);
        if($response && $response->nErrorCode == 0){
            $this->hcoin     = $response->stPrivateInfo->nGameCoin;
            $this->role_name = $response->stPublicInfo->szRoleName;
            return $this->hcoin >= $this->gamecoin ? true : false;
        }
        return false;
    }

    //投票次数
    public function _vote_time($uin, $zoneid){
        $day   = date("Ymd");
        $where = "uin={$uin} limit 1";

        //_vote表，一个投票的用户只有一条记录，  每次投票只更新：vote_day   vote_count
        $list = $this->model->get_item('bbpx2016_vote', 'vote_count,vote_day', $where);
        if(!empty($list)){
            if($day != $list[0]['vote_day']){
                //今天还没有投票
                $this->model->update_data('bbpx2016_vote', array('vote_count' => 0, 'vote_day' => $day), $where);
                return true;
            }
            //每次投票的时候更新： vote_count
            return $list[0]['vote_count'] < $this->limit ? true : false;
        }else{
            //用户还没有投过票，vote表 插入记录
            $param = array('uin' => $uin, 'zone_id' => $zoneid, 'vote_day' => $day, 'vote_count' => 0);
            $this->model->insert_data('bbpx2016_vote', $param);
            return true;
        }
    }

    /*
        *扣费
        *$type 1 游戏币 2 51点
        */
    private function reduceMoney($type, $num, $uin, $zoneid){
        load_extend('PromoterBill');
        $gm_server = new gm_server();
        $langMoney = Array(1 => '游戏币', 2 => '51点');
        if($type == 1){
            $money_type = 0x08;
        }elseif($type == 2){
            $money_type = 0x20;
        }
        $reduce = $num;
        //预发布修改扣费金额
        //$reduce = 1;
        $email            = array();
        $email['is_mail'] = 0;
        $email['sender']  = '系统信息';
        $email['content'] = "您好，您已成功扣除玫瑰明星大评选活动{$reduce}（{$langMoney[$type]}）。";
        $response         = $gm_server->send51Point($uin, 1, $zoneid, 'admin', 1, $money_type, 0 - $reduce, $email, '', 111, 0x09020027);
        if($response){
            if($response->nErrorCode != '0'){
                $statu = $response->nErrorCode;
            }else{
                $statu = 1;
            }
        }else{
            $statu = 0;
        }
        unset($response);
        return $statu;
    }

    //时间 && 登录的前提条件判断
    function is_off($login){
        $result = array('success' => 1);
        $time   = time();
        if($time < strtotime($this->time1)){
            $result['msg'] = '亲~本次活动尚未开始哦~';
            echo json_encode($result);
            exit;
        }
        if($time < strtotime($this->time2)){
            $result['msg'] = '现在是报名时间，投票还没开始';
            echo json_encode($result);
            exit;
        }
        if($time > strtotime($this->time3)){
            $result['msg'] = '亲，投票时间已结束~更多精彩活动请关注官网活动专区';
            echo json_encode($result);
            exit;
        }

        if($login == 0){
            $result['success'] = 2;
            $result['msg']     = '亲，还没有登录哦';
            return $result;
        }
    }
}